package cn.changeforyou.demo.netty.client;

import cn.changeforyou.demo.netty.common.Data;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhyu
 */

public class HeartbeatHandler extends ChannelInboundHandlerAdapter {

    Logger log = LoggerFactory.getLogger(HeartbeatHandler.class);

    public HeartbeatHandler(String token) {
        this.token = token;
    }

    private String token;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            if (idleStateEvent.state() == IdleState.WRITER_IDLE) {
                if (log.isDebugEnabled()) {
                    log.debug("心跳包发送");
                }
                //向服务端送心跳包
                //发送心跳消息，并在发送失败时关闭该连接
                ctx.writeAndFlush(Data.instanceHeartBeat()).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("捕获的异常：" + cause.getMessage());
        ctx.channel().close();
    }

}
